//
//  ViewController.m
//  07-nsurlsession04-大文件下载的进度
//
//  Created by J on 16/2/26.
//  Copyright © 2016年 J. All rights reserved.
//

#import "ViewController.h"
#define resumeDataFile [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"resumeData.temp"]
@interface ViewController ()<NSURLSessionDownloadDelegate>
@property(nonatomic,strong)NSURLSessionDownloadTask* task;

@property (weak, nonatomic) IBOutlet UIProgressView *progress;
@property(nonatomic,strong)NSData* resumeData;
@property(nonatomic,strong)NSURLSession* session;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}


- (void)downLoad{
    

    NSURLSessionDownloadTask* task = [self.session downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://download.wavetlan.com/SVV/Media/HTTP/H264/Talkinghead_Media/H264_test1_Talkinghead_mp4_480x360.mp4"]]];
    self.task = task;
    [task resume];
}
- (IBAction)start:(id)sender {//开始
    
    if (self.resumeData) {
        self.task =  [self.session downloadTaskWithResumeData:self.resumeData];//resumeData记录了上一次与服务器的沟通信息
        //将上次的临时文件放倒tem中
        [self.task resume];//调用才会下载
        
    }else{
    [self downLoad];
    }
}


- (NSData *)resumeData{
    if (!_resumeData) {
        self.resumeData = [NSData dataWithContentsOfFile:resumeDataFile];
    }
    return _resumeData;
}
- (NSURLSession *)session{
    if (!_session) {
        
        NSOperationQueue* queue = [[NSOperationQueue alloc] init];
        queue.name  = @"downLoad";
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:queue ];//获得
    }
    return _session;
}

- (IBAction)pause:(id)sender {//一旦被取消就无法恢复了 和服务器断开了

//    [self.task suspend];
    [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {//上一次下载数据
        self.resumeData = resumeData;//这是一个临时block不会发生循环
//        NSString* path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"resumeData.temp"];
        [self.resumeData writeToFile:resumeDataFile atomically:YES];//写入沙盒 保存起来下次进入app调用继续下载
        //缓存文件
        NSString* temp = NSTemporaryDirectory();
        NSFileManager* manager = [NSFileManager defaultManager];
        NSArray* subPath = [manager subpathsAtPath:temp];
        NSString* cach = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString*file = [temp stringByAppendingPathComponent:[subPath lastObject]];
        NSString* cachFile = [cach stringByAppendingPathComponent:[file lastPathComponent]];
        [manager moveItemAtPath:file toPath:cachFile error:nil];

        [@{@"tempFile":cachFile} writeToFile:[cach stringByAppendingPathComponent:@"tempFile.plist"] atomically:YES];
        
    
    }];
}
- (IBAction)goOn:(id)sender {//继续
    //重新下载会返回一个新的对象 保存起来
    self.task =  [self.session downloadTaskWithResumeData:self.resumeData];//resumeData记录了上一次与服务器的沟通信息
    [self.task resume];//调用才会下载

//    [[NSMutableURLRequest requestWithURL:@""] setValue:@"0-1024" forHTTPHeaderField:@"Range"];
}

#pragma mark --NSURLSessionDownloadDelegate


//恢复下载调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
    NSLog(@"didResumeAtOffset");

}


//没当写入数据到临时文件时,就会调用一次 多次调用
//totalBytesExpectedToWrite总大小
//totalBytesWritten已经写入大小
//bytesWritten这次写入多少
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    NSLog(@"%f",1.0*totalBytesWritten/totalBytesExpectedToWrite);//要让其中一个变为float计算出的结果才是float
    //    NSLog(@"%f",totalBytesWritten/(totalBytesExpectedToWrite*1.0));

    dispatch_async(dispatch_get_main_queue(), ^{//协议方法都是在NSOperationQueue子线程厘米调用的
        self.progress.progress = 1.0*totalBytesWritten/totalBytesExpectedToWrite;
        
    });
}

//下载完毕调用一次
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    NSLog(@"didFinishDownloadingToURL");

    //将来要存放的文件真实路径
    NSString* file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:downloadTask.response.suggestedFilename];//服务器给的文件名 104527c7dbbb3d3jjkckcb.jpg
    
    
    UIImage * image = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
    NSLog(@"%@",image);
    
    UIImageView* imageView = [[UIImageView alloc]initWithImage:image];
    dispatch_async(dispatch_get_main_queue(), ^{//下载会被放到分线程中
        imageView.center = self.view.center;
        //           imageView.backgroundColor = [UIColor orangeColor];
        NSLog(@"%@",imageView.image);
        [self.view addSubview:imageView];
        
    });
    NSFileManager* manager = [NSFileManager defaultManager];
    [manager moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
    
    
}


//任务完毕
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    //保存恢复数据
    self.resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
    
}


/*
 请求这个路径:http://download.wavetlan.com/SVV/Media/HTTP/H264/Talkinghead_Media/H264_test1_Talkinghead_mp4_480x360.mp4
 //设置请求头
 Range: 1024 - 2000 下载范围
 [[NSMutableURLRequest requestWithURL:@""] setValue:@"0-1024" forHTTPHeaderField:@"Range"];


*/


@end
